import functools

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for, send_from_directory, current_app
)
from werkzeug.security import check_password_hash, generate_password_hash

from .db import get_db

bp = Blueprint('auth', __name__, url_prefix='/auth')


@bp.route('/register', methods=('GET', 'POST'))
def register():
    if request.method == 'POST':
        uid = request.form['uid']
        password = request.form['password']
        db = get_db()
        error = None

        if not uid:
            error = 'uid is required.'
        elif not password:
            error = 'Password is required.'

        if error is None:
            db.execute(
                "INSERT INTO _user VALUES (%s, %s, null, null)",
                (uid, generate_password_hash(password))
            )
        else:
            return redirect(url_for("auth.login"))

        flash(error)

    return send_from_directory(current_app.root_path+'/static','reg.html')


@bp.route('/login', methods=('GET', 'POST'))
def login():
    if request.method == 'POST':
        uid = request.form['uid']
        password = request.form['password']
        db = get_db()
        error = None
        db.execute(
            f'SELECT * FROM _user WHERE uid = {uid}'
        )
        user = db.fetchone()

        if user is None:
            error = 'Incorrect uid.'
            print("uid戳了")
        elif not check_password_hash(user[1], password):
            error = 'Incorrect password.'
            print("密麻麻戳了")

        if error is None:
            session.clear()
            session['UID'] = user[0]
            return redirect(url_for('drawing.text2img'))

        flash(error)
        print("戳了")


    return send_from_directory(current_app.root_path+'/static','login.html')


@bp.before_app_request
def load_logged_in_user():
    uid = session.get('UID')
    # print(uid)
    if uid is None:
        g.user = None
    else:
        db = get_db()
        db.execute(
            f"SELECT * FROM _user WHERE uid = '{uid}'"
        )
        user_tuple = db.fetchone()
        if user_tuple is None:
            g.user = None
            return

        g.user = {
            "uid": user_tuple[0],
            "password": user_tuple[1],
            "nickname": user_tuple[2],
            "email": user_tuple[3]
        }


@bp.route('/logout')
def logout():
    session.clear()
    return redirect(url_for('auth.login'))


def login_required(view):
    @functools.wraps(view)
    def wrapped_view(**kwargs):
        if g.user is None:
            return redirect(url_for('auth.login'))

        return view(**kwargs)

    return wrapped_view